package common

import (
	"encoding/json"
	"fmt"
	"kingbloc.sso/user"
	"kingbloc.util/util"
	"net/http"
	"strconv"
	"time"
)

var conf *util.Config = nil

func SetConfig(filepath string) *util.Config {
	if conf != nil {
		return conf
	}
	conf = new(util.Config)
	conf.Filepath = filepath
	return conf
}

func GetConfig() *util.Config {
	return conf
}

// 登录
func Login(res http.ResponseWriter, req *http.Request) {
	conf = GetConfig()

	loginOverdue := conf.Get("sysinfo", "loginOverdue")
	//
	if req.Method != "POST" {
		util.WriteJSON(res, 1)
		return
	}

	refName := req.FormValue("username")
	password := req.FormValue("password")
	if password == "" {
		password = "000000"
	}

	password = util.Md5EncodeForPassword(password)

	//数据安全校验、过滤
	mobOk := util.RegexpMobile.MatchString(refName)
	emailOk := util.RegexpEmail.MatchString(refName)
	//
	userA := new(user.User)
	if mobOk {
		userA.Mobile = refName
		userA = userA.ByMobile()
	} else if emailOk {
		userA.Email = refName
		userA = userA.ByEmail()
	} else {
		userA.Username = refName
		userA = userA.ByUsername()
	}
	// 用户不存在
	if userA == nil || userA.Id == 0 {
		//fmt.Println(userA)
		util.WriteJSON(res, 3)
		return
	}

	// 密码不对
	if userA.Password != password {
		//fmt.Println(password)
		//fmt.Println(userA.Password)
		util.WriteJSON(res, 4)
		return
	}
	//
	userjson := userA.Mobile + "_" + strconv.FormatInt(userA.Id, 10)
	var ref util.UUID = util.Rand()
	token := ref.Hex()
	//记录登录用户id
	state := &user.State{}
	state.DelOverdue(userjson)
	state.Token = token
	state.Userjson = userjson

	refTime, _ := time.ParseDuration(loginOverdue)
	state.Overdue = time.Now().Add(refTime)
	state.Add()
	//
	redisHost := conf.Get("redis", "host")
	redisPort := conf.Get("redis", "port")
	redisDB, _ := strconv.Atoi(conf.Get("redis", "db"))

	pc := util.GetRedisConn(redisHost+":"+redisPort, redisDB)
	if pc == nil {
		fmt.Println("error connection to database")
	}

	userToJson, _ := json.Marshal(userA)
	_, err := pc.Do("SETNX", token, userToJson)
	if err != nil {
		fmt.Println(err)
		return
	}

	//
	COOKIE_MAX_MAX_AGE := time.Hour * 24 / time.Second // 单位：秒。
	maxAge := int(COOKIE_MAX_MAX_AGE)
	cookieRef := &http.Cookie{
		Path:     "/",
		Name:     "SSOTOKEN",
		Value:    token,
		MaxAge:   maxAge,
		HttpOnly: false,
	}

	http.SetCookie(res, cookieRef)

	result := make(map[string]interface{})
	result["userinfo"] = *userA
	result["token"] = state.Token
	//ress, _ := json.Marshal(result)
	util.WriteJSON(res, result)
	//res.Write([]byte(ress))
}
